import React, { FC,useEffect } from 'react'
import { Typography, Space, Button, Checkbox, Form, Input,message } from 'antd'
import { UserAddOutlined } from '@ant-design/icons'
import { Link,useNavigate } from 'react-router-dom'
import { loginService } from '../service/user.ts'
import { useRequest } from 'ahooks'
import {setToken} from '../token/index.ts'
import './Register.css'
const { Title } = Typography
const USERNAME_KEY = 'USERNAME'
const PASSWORD_KEY = 'PASSWORD'

function rememberUser(username: string, password: string){
    localStorage.setItem(USERNAME_KEY,username)
    localStorage.setItem(PASSWORD_KEY,password)
}

function deleteUserFromStorage(username: string, password: string){
    localStorage.removeItem(USERNAME_KEY)
    localStorage.removeItem(PASSWORD_KEY)
}

function getUserInfoFromStorage(){
    return {
        username: localStorage.getItem(USERNAME_KEY),
        password: localStorage.getItem(PASSWORD_KEY)
    }
}


const Login: FC = () => {
    const [form] = Form.useForm() // 第三方hook
    useEffect(()=>{
        const {username,password} = getUserInfoFromStorage()
        form.setFieldsValue({username,password})
    },[form])

    const nav = useNavigate()
    const {run} = useRequest(
        async (values)=>{
            const { username, password } = values
            const data = await loginService(username, password)
            return data
        },
        {
            manual: true,
            onSuccess:(res)=>{
                // console.log('res',res)
                message.success('登录成功')
                // 存储token
                setToken(res.token)
                nav('/manage/list')
            }
        }
    )
    const onFinish = (values:any) => {
        console.log('Success:', values);
        const { username, password, remember } = values
        run(values)
        if(remember){
            rememberUser(username,password)
        }else{
            deleteUserFromStorage(username,password)
        }
    };
    const onFinishFailed = (errorInfo:any) => {
        console.log('Failed:', errorInfo);
    };

    return (
        <div className="containerRegister">
            <div>
                <Space>
                    <Title level={2}>
                        <UserAddOutlined />
                    </Title>
                    <Title level={2}>
                        登录
                    </Title>
                </Space>
            </div>
            <div>
                <Form
                    name="basic"
                    labelCol={{span: 8}}
                    wrapperCol={{span: 16}}
                    style={{maxWidth: 600}}
                    initialValues={{remember: true}}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                    form={form}
                >
                    <Form.Item
                        label="用户名"
                        name="username"
                        rules={[
                            {required: true, message: '请输入用户名'},
                            {type: 'string',min:5,max:20,message:'字符长度在5-20之间'},
                            {pattern: /^\w+$/, message:"只能是字母数字下划线"}
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="密码"
                        name="password"
                        rules={[ {required: true,message: '请输入密码'}]}
                    >
                        <Input.Password />
                    </Form.Item>
                    {/* <Form.Item
                        label="确认密码"
                        name="confirm"
                        rules={[ {required: true,message: 'Please input your password!'}]}
                    >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item
                        label="昵称"
                        name="nickname"
                        rules={[ {required: false,message: 'Please input your password!'}]}
                    >
                        <Input.Password />
                    </Form.Item> */}
                    <Form.Item name="remember" valuePropName="checked" label={null}>
                        <Checkbox>记住我</Checkbox>
                    </Form.Item>

                    <Form.Item label={null}>
                        <Button type="primary" htmlType="submit">
                            登录
                        </Button>
                        <Link to="/register">注册新用户</Link>
                    </Form.Item>
                </Form>
            </div>
        </div>
    )
}


export default Login

